package com.ziytek.web.citizen.util;


import com.ziytek.web.citizen.constant.NumConstant;
import lombok.extern.slf4j.Slf4j;

import java.math.BigInteger;
import java.nio.ByteBuffer;

/**
 * @author fenghx
 * @version v1.0
 * @className HexUtil
 * @descripton 功能描述
 * @date 2023/4/13 11:01
 **/
@Slf4j
public class HexUtil {
    /**
     * 用于建立十六进制字符的输出的小写字符数组
     */
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 用于建立十六进制字符的输出的大写字符数组
     */
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


    /**
     * 十六进制转INT
     */
    public static int hexStrToInt(String hex) {
        try {
            return new BigInteger(hex, NumConstant.INT_TEN_SIX).intValue();
        } catch (Exception e) {
            log.error("hexToInt error:", e);
        }
        return NumConstant.INT_LT_ZERO;
    }

    /**
     * 字符串转换成十六进制字符串
     *
     * @param str 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str) {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder();
        byte[] bs = str.getBytes();
        int bit;

        for (byte b : bs) {
            bit = (b & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = b & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 十六进制转换字符串
     *
     * @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B])
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hex = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / NumConstant.INT_TWO];
        int n;

        for (int i = NumConstant.INT_ZERO; i < bytes.length; i++) {
            n = str.indexOf(hex[NumConstant.INT_TWO * i]) * NumConstant.INT_TEN_SIX;
            n += str.indexOf(hex[NumConstant.INT_TWO * i + NumConstant.INT_ONE]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * bytes转换成十六进制字符串
     *
     * @param b byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder();
        for (byte value : b) {
            stmp = Integer.toHexString(value & 0xFF);
            sb.append((stmp.length() == NumConstant.INT_ONE) ? "0" + stmp : stmp);
        }
        return sb.toString().toUpperCase().trim();
    }

    /**
     * bytes字符串转换为Byte值
     *
     * @param src Byte字符串，每个Byte之间没有分隔符
     * @return byte[]
     */
    public static byte[] hexStr2Bytes(String src) {
        int m = NumConstant.INT_ZERO, n = NumConstant.INT_ZERO;
        int l = src.length() / NumConstant.INT_TWO;
        System.out.println(l);
        byte[] ret = new byte[l];
        for (int i = NumConstant.INT_ZERO; i < l; i++) {
            m = i * NumConstant.INT_TWO + NumConstant.INT_ONE;
            n = m + NumConstant.INT_ONE;
            ret[i] = Byte.decode("0x" + src.substring(i * NumConstant.INT_TWO, m) + src.substring(m, n));
        }
        return ret;
    }

    /**
     * String的字符串转换成unicode的String
     *
     * @param strText 全角字符串
     * @return String 每个unicode之间无分隔符
     */
    public static String strToUnicode(String strText) throws Exception {
        char c;
        StringBuilder str = new StringBuilder();
        int intAsc;
        String strHex;
        for (int i = NumConstant.INT_ZERO; i < strText.length(); i++) {
            c = strText.charAt(i);
            intAsc = (int) c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128) {
                str.append("\\u").append(strHex);
            } else { // 低位在前面补00
                str.append("\\u00").append(strHex);
            }
        }
        return str.toString();
    }

    /**
     * unicode的String转换成String的字符串
     *
     * @param hex 16进制值字符串 （一个unicode为2byte）
     * @return String 全角字符串
     */
    public static String unicodeToString(String hex) {
        int t = hex.length() / NumConstant.INT_SIX;
        StringBuilder str = new StringBuilder();
        for (int i = NumConstant.INT_ZERO; i < t; i++) {
            String s = hex.substring(i * NumConstant.INT_SIX, (i + NumConstant.INT_ONE) * NumConstant.INT_SIX);
            // 高位需要补上00再转
            String s1 = s.substring(NumConstant.INT_TWO, NumConstant.INT_FOUR) + "00";
            // 低位直接转
            String s2 = s.substring(NumConstant.INT_FOUR);
            // 将16进制的string转为int
            int n = Integer.valueOf(s1, NumConstant.INT_TEN_SIX) + Integer.valueOf(s2, NumConstant.INT_TEN_SIX);
            // 将int转换为字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data byte[]
     * @return 十六进制char[]
     */
    public static char[] encodeHex(byte[] data) {
        return encodeHex(data, true);
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data        byte[]
     * @param toLowerCase <code>true</code> 传换成小写格式 ， <code>false</code> 传换成大写格式
     * @return 十六进制char[]
     */
    public static char[] encodeHex(byte[] data, boolean toLowerCase) {
        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data     byte[]
     * @param toDigits 用于控制输出的char[]
     * @return 十六进制char[]
     */
    protected static char[] encodeHex(byte[] data, char[] toDigits) {
        int l = data.length;
        char[] out = new char[l << NumConstant.INT_ONE];
        // two characters form the hex value.
        for (int i = NumConstant.INT_ZERO, j = NumConstant.INT_ZERO; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> NumConstant.INT_FOUR];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return out;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data byte[]
     * @return 十六进制String
     */
    public static String encodeHexStr(byte[] data) {
        return encodeHexStr(data, true);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data        byte[]
     * @param toLowerCase <code>true</code> 传换成小写格式 ， <code>false</code> 传换成大写格式
     * @return 十六进制String
     */
    public static String encodeHexStr(byte[] data, boolean toLowerCase) {
        return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data     byte[]
     * @param toDigits 用于控制输出的char[]
     * @return 十六进制String
     */
    protected static String encodeHexStr(byte[] data, char[] toDigits) {
        return new String(encodeHex(data, toDigits));
    }

    /**
     * 将十六进制字符数组转换为字节数组
     *
     * @param data 十六进制char[]
     * @return byte[]
     * @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度，将抛出运行时异常
     */
    public static byte[] decodeHex(char[] data) {

        int len = data.length;

        if ((len & 0x01) != NumConstant.INT_ZERO) {
            throw new RuntimeException("Odd number of characters.");
        }

        byte[] out = new byte[len >> NumConstant.INT_ONE];

        // two characters form the hex value.
        for (int i = NumConstant.INT_ZERO, j = NumConstant.INT_ZERO; j < len; i++) {
            int f = toDigit(data[j], j) << NumConstant.INT_FOUR;
            j++;
            f = f | toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    /**
     * 将十六进制字符转换成一个整数
     *
     * @param ch    十六进制char
     * @param index 十六进制字符在字符数组中的位置
     * @return 一个整数
     * @throws RuntimeException 当ch不是一个合法的十六进制字符时，抛出运行时异常
     */
    protected static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, NumConstant.INT_TEN_SIX);
        if (digit == NumConstant.INT_LT_ZERO) {
            throw new RuntimeException("Illegal hexadecimal character " + ch
                    + " at index " + index);
        }
        return digit;
    }


    /**
     * 接收字节数据并转换为16进制字符串
     *
     * @param by Byte数组
     * @return String
     */
    public static String receiveHexToString(byte[] by) {
        try {
            String str = bytes2Str(by);
            if (StringUtil.isEmpty(str)) {
                return null;
            }
            str = str.toUpperCase();
            return str;
        } catch (Exception ex) {
            log.info("接收字节数据并转为16进制字符串异常:", ex);
        }
        return null;
    }

    /**
     * 字节数组转换为16进制字符串
     *
     * @param src src
     * @return string
     */
    public static String bytes2Str(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length == NumConstant.INT_ZERO) {
            return null;
        }
        for (int i = NumConstant.INT_ZERO; i < src.length; i++) {
            if (i > NumConstant.INT_ZERO) {
                stringBuilder.append(" ");
            }
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < NumConstant.INT_TWO) {
                stringBuilder.append(NumConstant.INT_ZERO);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 字节转换为16进制字符
     *
     * @param src src
     * @return string
     */
    public static String byte2Str(byte src) {
        StringBuilder stringBuilder = new StringBuilder();
        int v = src & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < NumConstant.INT_TWO) {
            stringBuilder.append(NumConstant.INT_ZERO);
        }
        stringBuilder.append(hv.toUpperCase());
        return stringBuilder.toString();
    }

    /**
     * 十六进制转INT
     */
    public static int hexToInt(String hex) {
        try {
            return new BigInteger(hex, NumConstant.INT_TEN_SIX).intValue();
        } catch (Exception e) {
            log.info("hexToInt error:", e);
            return NumConstant.INT_ZERO;
        }
    }

    public static String intToHex(int dec) {
        try {
            return Integer.toString(dec, NumConstant.INT_TEN_SIX);
        } catch (Exception ignored) {
        }
        return "";
    }

    public static String bin2hex(String input) {
        StringBuilder sb = new StringBuilder();
        int len = input.length();
        for (int i = NumConstant.INT_ZERO; i < len / NumConstant.INT_FOUR; i++) {
            //每4个二进制位转换为1个十六进制位
            String temp = input.substring(i * NumConstant.INT_FOUR, (i + NumConstant.INT_ONE) * NumConstant.INT_FOUR);
            int tempInt = Integer.parseInt(temp, 2);
            String tempHex = Integer.toHexString(tempInt).toUpperCase();
            sb.append(tempHex);
        }

        return sb.toString();
    }

    /**
     * 十六进制转Float
     */
    public static Float hexStrToFloat(String hex) {
        try {
            int intNum = hexStrToInt(hex);
            // 使用putInt()直接将int值写入ByteBuffer
            ByteBuffer destBuffer = ByteBuffer.allocate(NumConstant.INT_FOUR);
            destBuffer.putInt(intNum);
            // 切换到读模式，因为我们要读取数据
            destBuffer.flip();
            return destBuffer.getFloat();
        } catch (Exception e) {
            log.info("hexStrToFloat error:", e);
            return NumConstant.FLOAT_ZER;
        }
    }

    /**
     * 十六进制转Float
     */
    public static Integer hexFloatToInt(Float floatNum) {
        try {
            //int intNum = hexStrToInt(hex);
            // 使用putInt()直接将int值写入ByteBuffer
            ByteBuffer destBuffer = ByteBuffer.allocate(NumConstant.INT_FOUR);
            destBuffer.putFloat(floatNum);
            // 切换到读模式，因为我们要读取数据
            destBuffer.flip();
            return destBuffer.getInt();
        } catch (Exception e) {
            log.info("hexStrToFloat error:", e);
            return NumConstant.INT_ZERO;
        }
    }


    public static short hexToShort(String hex) {
        try {
            int i = new BigInteger(hex, 16).intValue();
            return (short) i;
        } catch (Exception e) {
            log.info("hexToInt error:", e);
            return 0;
        }
    }


    // 不足14位的前补0
    public static String fillZero(String data) {
        return fillZero(data, NumConstant.INT_FORTY);
    }

    // 不足11位的前补0
    public static String fillZero(String data, int len) {
        if (StringUtil.isEmpty(data) || data.length() >= len) {
            return data;
        }

        int dataLen = data.length();
        return "0".repeat(len - dataLen - NumConstant.INT_ZERO) +
                data;
    }

    /**
     * @param src 16进制字符串
     * @return 字节数组
     */

    public static byte[] hexString2Bytes(String src) {
        int l = src.length() / NumConstant.INT_TWO;
        byte[] ret = new byte[l];

        for (int i = NumConstant.INT_ZERO; i < l; i++) {
            ret[i] = (byte) Integer.valueOf(src.substring(i * NumConstant.INT_TWO, i * NumConstant.INT_TWO + NumConstant.INT_TWO),
                    NumConstant.INT_TEN_SIX).byteValue();
        }

        return ret;
    }
}

